package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.mylb.MyLB;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class OrderController {
	//private final static String PAYMENT_URL = "http://localhost:8001";//不集群
	private final static String PAYMENT_URL = "http://cloud-payment-service";//集群
	
	@Autowired
	private MyLB lb;
	
	@Resource
	private RestTemplate restTemplate;
	
	@PostMapping("/consumer/payment")
	private CommonResult<Payment> create(Payment payment){
		log.info(payment.getSerial());
		return restTemplate.postForObject(PAYMENT_URL + "/payment",payment, CommonResult.class);
	}
	
	@GetMapping("/consumer/payment/{id}")
	public CommonResult<Payment> getPaymentById(@PathVariable("id") long id){
		return restTemplate.getForObject(PAYMENT_URL + "/payment/"+id,CommonResult.class);
	}
	
	@PostMapping("/consumer/payment/entity")
	private CommonResult<Payment> createforEntity(Payment payment){
		ResponseEntity<CommonResult> entity = restTemplate.postForEntity(PAYMENT_URL + "/payment", payment, CommonResult.class);
		if (entity.getStatusCode().is2xxSuccessful()){
			return entity.getBody();
		} else {
			return new CommonResult<>(500,"插入失败");
		}
	}
	
	@GetMapping("/consumer/payment/entity/{id}")
	public CommonResult<Payment> getPaymentByIdforEntity(@PathVariable("id") long id){
		ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/" + id, CommonResult.class);
		if (entity.getStatusCode().is2xxSuccessful()){
			return entity.getBody();
		} else {
			return new CommonResult<>(404,"查询失败");
		}
	}
	
	@GetMapping("/consumer/payment/lb/{id}")
	public CommonResult<Payment> getPaymentLBById(@PathVariable("id") long id){
		ServiceInstance service = lb.getService("cloud-payment-service");
		return restTemplate.getForObject(service.getUri() + "/payment/"+id,CommonResult.class);
	}
	
	@GetMapping("/consumer/payment/timeout")
	public String feginTimeout(){
		return restTemplate.getForObject(PAYMENT_URL + "/payment/timeout",String.class);
	}
}
